package com.ken.apollo.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ken.apollo.domain.query.SysDataQuery;
import com.ken.apollo.mapper.SysDataConfigMapper;
import com.ken.apollo.domain.entity.SysDataConfig;
import com.ken.apollo.service.LanguageService;
import com.ken.apollo.service.SysDataConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 常量数据表(SysDataConfig)表服务实现类
 *
 * @author makejava
 * @since 2025-06-09 20:11:42
 */
@Service
public class SysDataConfigServiceImpl extends ServiceImpl<SysDataConfigMapper, SysDataConfig> implements SysDataConfigService {

    @Autowired
    private LanguageService languageService;

    /**
     * 根据key搜索列表
     */
    @Override
    public List<SysDataConfig> list(SysDataQuery sysDataQuery) {
        //获取所有常量数据
        List<SysDataConfig> dataConfigs = this.lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(sysDataQuery.getLanguageId()), SysDataConfig::getLanguageId, sysDataQuery.getLanguageId())
                .like(ObjectUtil.isNotEmpty(sysDataQuery.getKey()), SysDataConfig::getDataKey, sysDataQuery.getKey())
                .orderByAsc(SysDataConfig::getDataKey)
                .orderByAsc(SysDataConfig::getLanguageId)
                .list();

        if (ObjectUtil.isEmpty(dataConfigs)) return List.of();

        //获取语言列表
        Map<Long, String> languageNameMaps = Optional.ofNullable(languageService.list())
                .orElse(new ArrayList<>()).stream()
                .collect(Collectors.toMap(language -> language.getId(), language -> language.getLanguageName()));

        //设置常量数据所属语言名称
        return dataConfigs.stream().map(dataConfig -> {
            dataConfig.setLanguageName(languageNameMaps.get(dataConfig.getLanguageId()));
            return dataConfig;
        }).collect(Collectors.toList());
    }
}

